package it.allerj.common.utility;

import java.lang.reflect.Field;
import java.util.Comparator;

public class ComparatorUtil<T> implements Comparator<T>{
	
	private String fieldName;

	/**
	 * 
	 * @param whichField this is the name field necessary to identify in which way order the objects in the collection
	 */
	public ComparatorUtil(String whichField){
		this.fieldName = whichField;
	}

	@SuppressWarnings("unchecked")
	public int compare(T obj1, T obj2) {
		try {
			Field obj1Field = obj1.getClass().getDeclaredField(fieldName);
			obj1Field.setAccessible(true);
			Object value1 = obj1Field.get(obj1);
			
			Field obj2Field = obj2.getClass().getDeclaredField(fieldName);
			obj2Field.setAccessible(true);
			Object value2 = obj1Field.get(obj2);
	
			if(value1 instanceof Comparable) {
				return ((Comparable<Object>)value1).compareTo(value2);
			}
			if(value1 instanceof Number){
				double result =((Number)value1).doubleValue()-((Number)value2).doubleValue();
				if(result>0)
					return 1;
				if(result<0)
					return -1;
				return 0;
			}
			return  obj1.toString().compareTo(obj2.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return 0;
		
	}

}
